<template>
<div>
  <TopTitle title="我要预约-请填写您的信息" />
  <el-form ref="form" :model="form" :rules="rules" label-width="110px" class="subcribeForm">
    <el-card class="clearfix">
      <div slot="header">
        <span class="clearSpan">基本信息</span>
      </div>
      <el-form-item label="来 访 时 间" prop="visitTime">
        <!-- <el-date-picker
          v-model="form.visitTime"
          type="datetime"
          placeholder="请选择日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm:ss"
          :picker-options="pickerOptions"
          @change="dateChange1">
        </el-date-picker> -->
        <div @click="showPicker = true">
              <el-input readonly v-model="form.visitTime" placeholder="请选择日期"></el-input>
        </div>
        <van-popup v-model="showPicker" position="bottom">
          <van-datetime-picker
            v-model="changeVisitDate"
            type="datetime"
            @confirm="onVisitConfirm"
            @cancel="showPicker = false"
            :min-date="minDate"
            title="请选择日期"
          />
        </van-popup>
      </el-form-item>
      <el-form-item label="截 止 时 间" prop="leaveTime">
        <!-- <el-date-picker
          v-model="form.leaveTime"
          type="datetime"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="请选择日期"
          :picker-options="pickerOptions"
          @change="dateChange2">
        </el-date-picker> -->
        <div @click="showLeavePicker = true">
          <el-input readonly v-model="form.leaveTime" placeholder="请选择日期"></el-input>
        </div>
        <van-popup v-model="showLeavePicker" position="bottom">
          <van-datetime-picker
            v-model="changeLeaveDate"
            type="datetime"
            @confirm="onLeaveConfirm"
            @cancel="showLeavePicker = false"
            :min-date="minLeaveDate"
            :max-date="maxLeaveDate"
            title="请选择日期"
          />
        </van-popup>
      </el-form-item>
      <el-form-item label="被访人手机" prop="contactNumber">
        <el-input v-model="form.contactNumber" placeholder="请输入手机号码"></el-input>
      </el-form-item>
      <el-form-item label="被访人姓名" prop="contacts">
        <el-input v-model="form.contacts" placeholder="请输入姓名"></el-input>
      </el-form-item>
      <el-form-item label="拜 访 事 由" prop="subjectMatter">
        <el-select v-model="form.subjectMatter" placeholder="请选择拜访事由" style="width: 100%;">
        <el-option
          v-for="item in subjectMatterOption"
          :key="item.dictCode"
          :label="item.dictValue"
          :value="item.dictValue">
        </el-option>
      </el-select>
      </el-form-item>
      <div class="otherUser" v-for="(item,index) in form.otherList" :key="index">
        <img src="../../assets/removeUser.png" alt="删" @click="removeUser(index)">
        <el-form-item 
        :label="'随访人员姓名'+(index+1)"
        :prop="`otherList[${index}].fullName`" 
        :rules="{
          required: true,
          message: '请输入随访人员姓名',
          trigger: 'blur'
        }"
        label-width="126px">
          <el-input v-model="item.fullName" placeholder="请输入随访人员姓名"></el-input>
        </el-form-item>
        <el-form-item 
          label-width="126px"
          :label="'随访人身份证号'+(index+1)"
          :prop="`otherList[${index}].idCard`" 
          :rules="{
            required: true,
            message: '请输入身份证号或身份证号有误',
            pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
            trigger: 'blur'
          }">
          <el-input v-model="item.idCard" placeholder="请输入随访人身份证号"></el-input>
        </el-form-item>
      </div>
      <div style="text-align: right;" v-show="form.otherList.length < 2">
        <el-button type="primary" @click="addUser" round>+ 随访人</el-button>
      </div>
    </el-card>
    <el-card class="clearfix otherClearfix">
      <div slot="header" class="headerOpr">
        <span class="clearSpan">其他信息</span>
        <p @click="otherShow = !otherShow">
          <span v-if="!otherShow">
            <i class="el-icon-arrow-down"></i>展开
          </span>
          <span v-else>
            <i class="el-icon-arrow-up"></i>收起
          </span>
          
        </p>
      </div>
      <div v-show="otherShow" class="otherContent">
        <el-form-item label="携带物品">
          <el-input v-model="form.goods" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="体温">
          <el-input v-model="form.temperature" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="车牌号">
          <el-input v-model="form.licensePlate" placeholder="请输入"></el-input>
        </el-form-item>
        <div class="uploadImg">
          <div class="uploadItem">
            <p>健康码</p>
            <el-upload
            class="avatar-uploader"
            action="/common/uploads"
            :show-file-list="false"
            :on-success="healthCodeSuccess">
            <img v-if="form.healthCode" :src="form.healthCode" alt="上传" class="avatar">
            <img v-else src="../../assets/defultImg.png" alt="上传" class="avatar-uploader-icon"/>
          </el-upload>
          </div>
          <div class="uploadItem">
            <p>行程码</p>
            <el-upload
            class="avatar-uploader"
            action="/common/uploads"
            :show-file-list="false"
            :on-success="travelCodeSuccess">
            <img v-if="form.travelCode" :src="form.travelCode" alt="上传" class="avatar">
            <img v-else src="../../assets/defultImg.png" alt="上传" class="avatar-uploader-icon"/>
          </el-upload>
          </div>
          <div class="uploadItem">
            <p>核酸检测</p>
            <el-upload
            class="avatar-uploader"
            action="/common/uploads"
            :show-file-list="false"
            :on-success="nucleicAcidSuccess">
            <img v-if="form.nucleicAcid" :src="form.nucleicAcid" alt="上传" class="avatar">
            <img v-else src="../../assets/defultImg.png" alt="上传" class="avatar-uploader-icon"/>
          </el-upload>
          </div>
        </div>
      </div>
    </el-card>
    <div style="display: flex;justify-content: center;margin: 41px 0;">
      <el-button type="primary" round style="width: 157px;" @click="pushRoute">我的信息</el-button>
      <el-button type="primary" round style="width: 157px;" @click="submit">发起预约</el-button>
    </div>
  </el-form>
  </div>
</template>

<script>
import { Message } from 'element-ui';
import { fetchPost, fetchGet } from '../../util';
import { dateUtils } from '../../util/utils'
export default {
  components: {
    TopTitle: () => import("../../components/Title")
  },
  data() {
    return {
      form: {
        visitTime: null,
        leaveTime: null,
        contactNumber: '',
        contacts: '',
        subjectMatter: '',
        goods: '',
        temperature: '',
        licensePlate: '',
        healthCode: '',
        travelCode: '',
        nucleicAcid: '',
        otherList: [],
      },
      rules: {
        visitTime: [{
          required: true,
          message: '请选择来访时间',
          trigger: 'change'
        }],
        leaveTime: [{
          required: true,
          message: '请选择截止时间',
          trigger: 'change'
        }],
        contactNumber: [{
          required: true,
          message: '请填写手机号或手机号有误',
          pattern: /^1[3456789]\d{9}$/,
          trigger: 'blur'
        }],
        contacts: [{
          required: true,
          message: '请填写被访人姓名',
          trigger: 'blur'
        }],
        subjectMatter: [{
          required: true,
          message: '请选择拜访事由',
          trigger: 'change'
        }],
      },
      subjectMatterOption: [],
      otherShow: false,
      minDate: new Date(),
      minLeaveDate: new Date(),
      changeVisitDate: new Date(),
      changeLeaveDate: new Date(),
      showPicker: false,
      showLeavePicker: false,
      maxLeaveDate: new Date(new Date(new Date().toLocaleDateString()).getTime()+24*60*60*1000-1)
    }
  },
  mounted() {
    this.form.visitTime = dateUtils('YYYY-mm-dd HH:MM:SS',new Date())
    if(sessionStorage.getItem("subcribeDate")) {
      this.form = JSON.parse(sessionStorage.getItem("subcribeDate"));
      sessionStorage.removeItem("subcribeDate");
    }
    if(sessionStorage.getItem("subcribeOtherList")) {
      this.form.otherList = JSON.parse(sessionStorage.getItem("subcribeOtherList"));
      sessionStorage.removeItem("subcribeOtherList");
    }
    this.getOption();
  },
  methods: {
    getOption() {
      fetchGet('/api/customerAppointment/selDictData?dictType=sys_customer_reason').then(data => {
        if(data?.code === 0) {
            this.subjectMatterOption = data?.data;
          }
      })
    },
    addUser() {
      this.form.otherList.push({fullName: '',idCard: ''});
    },
    removeUser(index) {
      this.form.otherList.splice(index,1);
    },
    healthCodeSuccess(res) {
      if(res.code === 0){
        this.form.healthCode = res.url;
      }
    },
    travelCodeSuccess(res) {
      if(res.code === 0){
        this.form.travelCode = res.url;
      }
    },
    nucleicAcidSuccess(res) {
      if(res.code === 0){
        this.form.nucleicAcid = res.url;
      }
    },
    timeFormat(time) { // 时间格式化 2019-09-08
      const y = time.getFullYear();
      const mt = time.getMonth() + 1;
      const d = time.getDate();
      const h = time.getHours() > 9 ? time.getHours() : `0${time.getHours()}`;           
      const m = time.getMinutes() > 9 ? time.getMinutes() : `0${time.getMinutes()}`;         
      const s = time.getSeconds() > 9 ? time.getSeconds() : `0${time.getSeconds()}`;
      return `${y}-${mt}-${d} ${h}:${m}:${s}`
    },
    onVisitConfirm(time) {
      this.form.visitTime = this.timeFormat(time);
      this.minLeaveDate = time;
      this.maxLeaveDate = new Date(new Date(new Date(time).toLocaleDateString()).getTime()+24*60*60*1000-1);
      this.form.leaveTime = null;
      this.showPicker = false;
    },
    onLeaveConfirm(time) {
      this.form.leaveTime = this.timeFormat(time);
      this.showLeavePicker = false;
    },
    pushRoute() {
      sessionStorage.setItem("subcribeDate",JSON.stringify(this.form));
      if(this.form.otherList.length > 0) {
        sessionStorage.setItem("subcribeOtherList",JSON.stringify(this.otherList));
      }
      this.$router.push('/userSubcribe?linkFrom=subcribe')
    },
    submit() {
      let pamars = {};
      this.form.otherList&&this.form.otherList.forEach((item,index) => {
        pamars[`fullName${index+1}`] = item.fullName;
        pamars[`idCard${index+1}`] = item.idCard;
      })
      //pamars.visitTime = this.form.visitTime.getFullYear() + '-' + (this.form.visitTime.getMonth() + 1) + '-' + this.form.visitTime.getDate() + ' ' + this.form.visitTime.getHours() + ':' + this.form.visitTime.getMinutes() + ':' + this.form.visitTime.getSeconds();
      this.$refs['form'].validate((valid) => {
					if (valid) {
            const baseMsg = sessionStorage.getItem("baseMsg") ? JSON.parse(sessionStorage.getItem("baseMsg")) : JSON.parse(sessionStorage.getItem("userInfo"))
            fetchPost("/api/customerAppointment/saveCustomerAppointment", {
              ...baseMsg,
              ...this.form,
              ...pamars,
              otherList: undefined,
            }).then(data=>{
              if(data?.code === 0) {
                Message({
                  message: '预约成功',
                  type: 'success'
                });
                sessionStorage.removeItem("baseMsg")
                this.getUserInfo();
              }
            })
          }
      })
    },
    getUserInfo() {
       fetchGet(`/api/customerAppointment/selByOpenid`).then(data=>{
        if(data.code === 0 && data.data) {
          sessionStorage.setItem("userInfo",JSON.stringify(data.data));
          this.$router.replace(`/detail?appointmentId=${data.data?.appointmentId}`);
        }
      })
    }
  }
}
</script>

<style scoped>
  .subcribeForm {
    margin-top: 46px;
  }
  .clearfix{
    margin-bottom: 16px;
  }
  .clearSpan{
    font-weight: bold;
    font-size: 18px;
  }
  .clearSpan::before{
    display: inline-block;
    content: '';
    width: 6px;
    height: 17px;
    background: #1890FF;
    position: relative;
    top: 3px;
    left: -4px;
    border-radius: 2px;
  }
  .headerOpr{
    display: flex;
    justify-content: space-between;
  }
  .headerOpr p{
    font-size: 16px;
  }

  .otherUser{
    padding: 15px;
    background: #F5FAFE;
    margin-bottom: 16px;
    position: relative;
  }
  .otherUser img{
    position: absolute;
    right: -7px;
    top: -7px;
    width: 16px;
    height: 16px;
  }
  .otherContent{
    padding: 20px;
  }

  .uploadImg{
    display: flex;
    flex-wrap: wrap;
  }

  .uploadItem{
    margin-right: 30px;
    margin-bottom: 15px;
  }

  .uploadImg p{
    font-size: 16px;
    font-weight: 400;
    text-align: center;
    margin-bottom: 10px;
  }
  
  .avatar {
    width: 101px;
    height: 101px;
    display: block;
  }
</style>
